import {_decorator} from 'cc';
import {BaseComponent} from "db://assets/scripts/framework/BaseComponent";
import {MessageType} from "db://assets/scripts/framework/MessageType";
import Message from "db://assets/scripts/framework/Message";
import {MessageCenter} from "db://assets/scripts/framework/MessageCenter";

const {ccclass, property} = _decorator;

@ccclass('BaseManager')
export class BaseManager extends BaseComponent {
    /**
     * 管理所有组件
     */
    receiveList: BaseComponent[] = [];
    /**
     * 消息类型
     */
    messageType: MessageType;

    onLoad() {
        // 设置消息类型
        this.messageType = this.getMessageType();
        // 把自己添加到消息中心
        MessageCenter.managers.push(this);
    }

    getMessageType(): MessageType {
        return MessageType.TYPE_UI;
    }

    registerReceiver(component: BaseComponent) {
        this.receiveList.push(component);
    }

    /**
     * 接收消息
     *
     * @param message 消息
     */
    receiveMessage(message: Message) {
        super.receiveMessage(message);
        // 当接收的消息不是本类型时
        if (message.type !== this.messageType) {
            // 直接返回
            return;
        }

        // 转发
        for (let component of this.receiveList) {
            // 向下转发消息
            component.receiveMessage(message);
        }
    }
}

